import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/cook_db_provider.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/collect/view/cook_item_cell.dart';
import 'package:flutter_douban/model/cook_info_model.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CollectionCookPage extends StatefulWidget {
  const CollectionCookPage({Key? key}) : super(key: key);

  @override
  _CollectionCookPageState createState() => _CollectionCookPageState();
}

class _CollectionCookPageState extends State<CollectionCookPage> {
  List<CookInfoModel> _cookInfoList = [];

  /// 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;
  StreamSubscription<CacheCookEvent>? _cacheCookSubscription;
  StreamSubscription<LoginEvent>? _loginSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();

    _loginSubscription = EventBusUtil.listen((event) {
      setState(() {
        getData();
      });
    });
    _cacheCookSubscription = EventBusUtil.listen((event) {
      setState(() {
        getData();
      });
    });
    getData();
  }

  Future<void> getData() async {
    CookDbProvider provider = new CookDbProvider();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(AppConfig.numberId);
    if(numberId == null){
      numberId = '123';
    }
    List<CookInfoModel> list = [];
    provider.getAllClassInfo(numberId).then((value) => {
      list = value,
      setState(() {
        _cookInfoList = list;
      }),
    });
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
        // 开启首次加载刷新
        firstRefresh: false,
        header: CustomHeaderView(),
        footer: CustomFooterView(),
        controller: _easyRefreshController,
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        onRefresh: getData,
        child: Container(
          color: Colors.white,
          child: ListView.builder(
            controller: _scrollController,
            itemCount: _cookInfoList.length,
            shrinkWrap: true, //增加
            itemBuilder: (BuildContext context, int index) {
              return CookItemCell(model: _cookInfoList[index]);
            },
          ),
        ));
    // }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _cacheCookSubscription?.cancel();
    super.dispose();
  }
}
